package com.sgb.kjwl.utils;

import android.content.Intent;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;

import androidx.activity.ComponentActivity;
import androidx.annotation.NonNull;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleEventObserver;
import androidx.lifecycle.LifecycleOwner;

import com.sgb.kjwl.service.ForegroundService;

/**
 * @author: 杨畔
 * @date: 4/14/21 2:44 PM
 * @Description: 保活工具
 */
public class KeepLifecycle implements LifecycleEventObserver {
    //相机保活列表
    public static String[] CAMERA_KEEP_MODEL = {
            "Redmi K20", "Redmi K20 Pro", "Redmi K30", "Redmi K30 5G",
    };
    //附着页面
    private final ComponentActivity activity;
    //保活服务
    private Intent mService;

    private KeepLifecycle(ComponentActivity activity) {
        this.activity = activity;
    }

    /**
     * 添加保活
     *
     * @param activity      附着页面
     * @param keepModelList 保活手机型号列表
     */
    public static void attach(ComponentActivity activity, String... keepModelList) {
        //当前手机型号
        String currentModel = Build.MODEL;
        //是否需要保活
        boolean isAttach = false;
        if (keepModelList == null || keepModelList.length == 0) {
            //保活列表没有值的时候默认全部手机型号都弹出保活前台通知
            isAttach = true;
        } else if (!TextUtils.isEmpty(currentModel)) {
            //格式化手机型号
            currentModel = currentModel.toLowerCase().trim();
            //判断当前手机型号是否在保活列表内
            for (String model : keepModelList) {
                //格式化手机型号
                if (TextUtils.isEmpty(model)) {
                    model = "";
                } else {
                    model = model.toLowerCase().trim();
                }
                //判断手机型号
                if (currentModel.equals(model)) {
                    isAttach = true;
                    break;
                }
            }
        }
        if (isAttach) {
            //添加生命周期监听
            KeepLifecycle lifecycle = new KeepLifecycle(activity);
            activity.getLifecycle().addObserver(lifecycle);
        }
    }

    @Override
    public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event) {
        if (event == Lifecycle.Event.ON_CREATE) {
            Log.e("KeepLifecycle", "ON_CREATE");
            mService = new Intent(activity, ForegroundService.class);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                activity.startService(mService);
            }
        } else if (event == Lifecycle.Event.ON_DESTROY) {
            Log.e("KeepLifecycle", "ON_DESTROY");
            if (mService != null) {
                activity.stopService(mService);
            }
            //移除生命周期监听
            activity.getLifecycle().removeObserver(this);
        }
    }
}
